#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-09-24 14:37
# @Author : hard work
# @File    : parse_pkt_base.py
# @Description :
import pyshark

from utils.my_loger import Log
from utils.parse_pkt_utils.pyshark_util.pyshark_util import progress_bar


class Parse_pcap_base:
    def __init__(self, file):
        self.mylog = Log()
        self.dst_mac_lst = []
        self.src_mac_lst = []
        self.vid_lst = []
        self.priority_lst = []
        self.seq_lst = []
        self.pkt_len_lst = []
        self.pkt_len_cnt = 0
        self.stc_sig_lst = []
        self.file = file
        self.PKT_LST = []
        # self.parse_pcap_to_any_list()

    def parse_pcap_to_any_list(self):
        """五元组放到每个列表中"""
        try:
            __pcap = pyshark.FileCapture(self.file)
            for pkt in __pcap:
                __dst_mac = str(pkt.eth.dst)
                self.dst_mac_lst.append(__dst_mac)

                __src_mac = str(pkt.eth.src)
                self.src_mac_lst.append(__src_mac)

                __vid = str(pkt.vlan.id)
                self.vid_lst.append(__vid)

                __priority = str(pkt.vlan.priority)
                self.priority_lst.append(__priority)

                __seq = str(pkt.IEEE8021CB.SEQ)
                hex_2_int__seq = int(__seq, 16)
                self.seq_lst.append(hex_2_int__seq)

                __pkt_len = str(pkt.length)
                self.pkt_len_lst.append(__pkt_len)

                __stc_trans_2_int = int(pkt.STCSIG.seqnum)
                self.stc_sig_lst.append(__stc_trans_2_int)

                self.pkt_len_cnt += 1

        except RuntimeError as e:
            print(e)
            self.mylog.ERROR_LOG("pyshark运行时发生错误")
        else:
            __pcap.close()

    def parse_pcap_to_one_list(self, file_path, wireshark_file):
        progress_bar("正在解析%s" % file_path)

        try:
            pcap = pyshark.FileCapture(file_path, tshark_path=wireshark_file + "\\tshark.exe")
            for pkt in pcap:
                self.PKT_LST.append(pkt)
            print("\nInfo ", "%s解析完毕" % file_path)
            return self.PKT_LST
        except RuntimeError as e:
            print("pyshark运行时发生错误", e)
        except FileExistsError as e:
            print("文件不存在", e)

    def compare_pkt_field_num(self, lst):
        cnt = 0
        while cnt < len(lst) - 1:
            if lst[cnt + 1] - 1 == lst[cnt]:
                self.mylog.NOTICE_LOG("第%s比较 %s 减去1 == %s " % (
                    cnt, lst[cnt + 1], lst[cnt]))
            else:
                self.mylog.WARNNING_LOG("第%s比较 %s 减去1 != %s " % (
                    cnt, lst[cnt + 1], lst[cnt]))
            cnt += 1

if __name__ == '__main__':
    pass
